<?php

namespace app\models\auth_app\pinduoduo;

use app\components\Func;
use app\models\AuthShop;
use Yii;
use app\models\AuthApp;

class AuthAppPinduoduo extends AuthApp
{
    const APP_ID = '111';
    const APP_SECRET = '222';
    const REDIRECT_URI = '3333';

    const URL_CONNECT = 'https://fuwu.pinduoduo.com/service-market/auth';
    const URL_API = 'https://gw-api.pinduoduo.com/api/router';


    //获取消息事件对象
    public function getMsgObj($data){
        if(empty($data)) return ;
        $msg_arr = json_decode($data, 1);

        $cname = ucfirst(strtolower(str_replace(['_',' '],'',$msg_arr['event'])));
        $cname = 'app\\models\\auth_app\\doudian\\msg\\'.$cname;
        if(!class_exists($cname))$cname = 'app\\models\\auth_app\\doudian\\msg\\msg0';
        $obj = new $cname();
        $obj->auth_app_id = $this->id;
        $obj->event = $msg_arr['event'];
        $obj->content = $data;
        if(!$obj->save()){
            throw new \Exception(json_encode($obj->getErrors(),JSON_UNESCAPED_UNICODE), 1);
        }
        return $obj;

    }
    //刷新token
    public function refreshToken(AuthShop $authShop){
        $arr = [
            'type'=>'pdd.pop.auth.token.refresh',
            'refresh_token'=> $authShop->refresh_token,
        ];
        $data = $this->getData($arr);
        $authShop->token = $data['access_token'];
        $authShop->token_expire_time = (time() + $data['expires_in']);
        $authShop->refresh_token = $data['refresh_token'];
        $authShop->refresh_token_expire_time = (time() + $data['refresh_token_expires_in']);
        if(!$authShop->save()){
            throw new \Exception(json_encode($authShop->getErrors(),JSON_UNESCAPED_UNICODE));
        }
    }
    //获取token
    public function getTokenByCode($code){
        $arr = [
            'type'=>'pdd.pop.auth.token.create',
            'code'=>$code,
        ];
        $data = $this->getData($arr);
        return $data;
    }
    public function initToken($code){
        $token_arr = $this->getTokenByCode($code);
        $authShop = AuthShop::findOne(['auth_app_shop_id'=>$token_arr['owner_id']]);
        if(empty($authShop)){
            $authShop = new AuthShop();
            $authShop->auth_app_id = $this->id;
            $authShop->auth_app_shop_id = $token_arr['owner_id'];
            $authShop->name = $token_arr['owner_name'];
            $authShop->ctime = time();
        }
        $authShop->uid = Yii::$app->user->id;
        $authShop->state = AuthShop::STATE_GOOD;
        $authShop->token = $token_arr['access_token'];
        $authShop->token_expire_time = (time() + $token_arr['expires_in']);
        $authShop->refresh_token = $token_arr['refresh_token'];
        $authShop->refresh_token_expire_time = (time() + $token_arr['refresh_token_expires_in']);
        if(!$authShop->save()){
            throw new \Exception(json_encode($authShop->getErrors(),JSON_UNESCAPED_UNICODE));
        }
        return $authShop;
    }
    //创建授权跳转链接
    public function buildConnectUrl($state=''){
        $arr = [
            'response_type'=> 'code',
            'client_id'=> self::APP_ID,
            'redirect_uri'=> self::REDIRECT_URI,
            'state'=> $state,
        ];
        return self::URL_CONNECT.'?'.http_build_query($arr);
    }
    //通用请求方法//自动生成sign，检测请求结果
    protected function getData($arr){
        $arr['client_id'] = self::APP_ID;
        $arr['timestamp'] = time();
        $arr['sign'] = $this->getSign($arr);
        $response = Func::file_get_contents(self::URL_API.'?'.http_build_query($arr));
        $data = self::checkResponse($response);
        return $data;
    }
    /**
     * 	作用：生成签名
     */
    protected function getSign($arr)
    {
        //签名步骤一：按字典序排序参数
        ksort($arr, SORT_STRING);
        $str = '';
        foreach ($arr as $key => $val) {
            $str.=$key.urlencode($val);
        }
        //签名步骤二：在string前后加入KEY
        $str = self::APP_SECRET.$str.self::APP_SECRET;
        //签名步骤三：MD5加密
        $str = md5($str);
        //echo "【string3】 ".$String."</br>";
        //签名步骤四：所有字符转为大写
        $str = strtoupper($str);
        //echo "【result】 ".$result_."</br>";
        return $str;
    }

    //检测并格式化抖音返回数据
    static public function checkResponse($response){
        $arr = json_decode($response,1);
        if(empty($arr)){
            Yii::error($response);
            throw new \Exception('拼多多接口返回错误',30000);
        }
        if(isset($arr['error_response'])){
            Yii::error($response);
            throw new \Exception('拼多多接口返回错误:'.$arr['error_response']['error_code'].":".$arr['error_response']['error_msg'],30000);
        }
        $data = current($arr);
        return $data;
    }

}
